package engine.logic.login
{
	import engine.data.GamePlayer;
	import engine.data.ModelLocator;
	import engine.event.BaseNetEvent;
	import engine.logic.ActSee;
	import engine.logic.AlertLogic;
	import engine.logic.event.LogicEvent;
	import engine.logic.loading.LoadingLogic;
	import engine.net.NetSocket;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.NetMgr;
	import engine.net.mgr.SystemSender;
	import engine.scene.SceneManager;
	import engine.ui.AlertTimeLoseUI;
	import engine.ui.AlertUI;
	
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.utils.getTimer;
	
	import newx.com.config.StaticIni;
	import newx.utils.debug.IO;

	public class UniteLogin implements ILoginLogic
	{	
		public static	var UICompleteFunc:Function = null;
		private var _create	:Boolean = false;
		
		public function UniteLogin(loginInfo:Object)
		{
			LoginLogic.LoginMode	=	LoginLogic.Mode_UniteLogin;
			
			_loginInfo=loginInfo;
			
			init();
//			LoginAlert2.showAlert("initUI....");
			
//			_loginUI.showLogin();
			
			LoginCallLater.callLater(
				LoginCallLater.UiResReady|LoginCallLater.ConfigDataReady,
				NetMgr.netConnect,
				[_loginInfo.ip,_loginInfo.port,socketConnectSucceedHandler]
			);
			
//			LoginShowQueue.callLater(
//				LoginShowQueue.UiResReady|LoginShowQueue.ConfigDataReady,
//				SystemSender.getInstance().Login,
//				[loginInfo.userName,loginInfo.password]
//			);
			
			LoginCallLater.callLater(
				LoginCallLater.UiResReady|LoginCallLater.ConfigDataReady,
				SystemSender.getInstance().LoginOtherWay,
				[_loginInfo.sAccount,_loginInfo.sIdentity]
			);
			
			LoginCallLater.callLater(LoginCallLater.UiResReady|LoginCallLater.ConfigDataReady,
				loginWaitingAni,null);
			
			
			IO.traceLog("联合运营登录,ip:",loginInfo.ip,"port:",loginInfo.port,"sAccount:",loginInfo.sAccount,"sIdentity:",loginInfo.sIdentity);
			
			LoginGroup._ip		=	loginInfo.ip;
			LoginGroup._port	= 	loginInfo.port;
			LoginGroup._userName=	loginInfo.sAccount;
			LoginGroup._password=	loginInfo.sIdentity;
			
			/**服务器IP*/
			ActSee.s_serverIp	=		loginInfo.ip;
			/**账号*/
			ActSee.s_account	=		loginInfo.sAccount;
			//	NetMgr.netConnect(loginInfo.ip,loginInfo.port,socketConnectSucceedHandler);
			//	SystemSender.getInstance().LoginOtherWay(loginInfo.sAccount,loginInfo.sIdentity);
		}
		
		private var _loginInfo:Object;
		
		private var _loginUI:LoginUI;
		
		private var _roleCreateInfo:Object;
		
		private var _resReadyCallBack:Function;
		
		/**
		 *	时间 
		 */
		private 			var _time		:int;
		
		private function init():void
		{
			this.invoke();
		}
		
		private function invoke():void
		{
			ModelLocator.getInstance().addEventListener(BaseNetEvent.LOGIN_SUCCESS,loginSuccessHandler);
			ModelLocator.getInstance().addEventListener(BaseNetEvent.SERVER_ERROR,loginFailHandler);
			
//			ModelLocator.getInstance().addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ROLE_CREATED),roleCreateReadyHandler);
			loginUI.completeCallBack=loginUIFeedBackHandler;
			
			ModelLocator.getInstance().addEventListener(BaseNetEvent.SERVER_QUEUE,serverQueueHandler);
			
			NetSocket.getInstance().addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandle);
			
			//			ModelLocator.getInstance().addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_PLAYER_NO_CASTLE),roleCreateReadyHandler);
			
			ModelLocator.getInstance().addEventListener(LogicEvent.INIT_COMPLETE,onGameInitComplete);
		
			//			ModelLocator.getInstance().addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_PLAYER_NO_CASTLE),roleCreateReadyHandler);
		}
		
		private function onGameInitComplete(e:LogicEvent):void
		{
			if(UICompleteFunc!=null)UICompleteFunc.call();
		}
			
		
		private function recycle():void
		{
//			ModelLocator.getInstance().removeEventListener(BaseNetEvent.LOGIN_SUCCESS,loginSuccessHandler);
//			ModelLocator.getInstance().removeEventListener(BaseNetEvent.SERVER_ERROR,loginFailHandler);
			
//			ModelLocator.getInstance().removeEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ROLE_CREATED),roleCreateReadyHandler);
			
			ModelLocator.getInstance().removeEventListener(BaseNetEvent.SERVER_QUEUE,serverQueueHandler);
			if(	null	!=	_loginUI)
			{
				_loginUI.completeCallBack=null;
				_loginUI.recycle();
				_loginUI	=	null;
			}
			
			LoginAlert.recycle();
		}
		
		private function loginWaitingAni():void
		{
//			WaitingForScene.start();
		}
		
		//登录界面 登录信息回调
		private function loginUIFeedBackHandler(loginInfo:Object):void
		{
			var type:String=loginInfo.type;

			if(LoginUI.FeedBackRoleCreate	==	type)
			{
				_time = getTimer();
				_create = true;
//				_loginInfo=loginInfo
				_roleCreateInfo=loginInfo;
				//send message
				
//				LoginShowQueue.callLater(
//										LoginShowQueue.ConfigDataReady|LoginShowQueue.UiResReady,
//										SystemSender.getInstance().CreatRole,
//										[loginInfo.roleName,loginInfo.raceId,0,0,loginInfo.occuId]
//										);
//				WaitingForScene.start();
				SystemSender.getInstance().CreatRole(loginInfo.roleName,loginInfo.raceId,loginInfo.sexId,0,loginInfo.occuId,getCastleById(_roleCreateInfo.castleId)	);
				
//				var castleStr:String	=  getCastleById(_roleCreateInfo.castleId);
//				
//				SystemSender.getInstance().CustomMsg(
//					CustomToServerFlag.CLIENT_CUSTOMMSG_APPLYIN_CASTLE,castleStr);
			}
		}
		
		private function socketConnectSucceedHandler():void
		{
			IO.traceLog("服务器连接成功");
			
			ModelLocator.getInstance().dispatchEvent(new LogicEvent(LogicEvent.CONNECT_SUCCESS));
		}
		
		private function socketConnectFailHandler(e:IOErrorEvent):void
		{
			AlertUI.showAlert(StaticIni.getSwfLangStr("MessageUI_Notice"),this.getConnectErrorMsg());
//			LoginAlert.showAlert(this.getConnectErrorMsg());
		}
		
//		private function roleCreateReadyHandler(e:CustomMsgEvent):void
//		{
//			SystemSender.getInstance().CustomMsg(
//				CustomToServerFlag.CLIENT_CUSTOMMSG_APPLYIN_CASTLE,getCastleById(_roleCreateInfo.castleId));
//		}
		
//		private function roleCreateReadyHandler(e:CustomMsgEvent):void
//		{
//			//			if(	1	==	e.pList[0])
//			//			{
//			if(	_roleCreateInfo	&&	_roleCreateInfo.hasOwnProperty("castleId"))
//			{
//				var castleStr:String	=  getCastleById(_roleCreateInfo.castleId);
//				
//				SystemSender.getInstance().CustomMsg(
//					CustomToServerFlag.CLIENT_CUSTOMMSG_APPLYIN_CASTLE,castleStr);
//			}
//			//			}
//		}
		
		/**服务器连接成功后发送登陆信息*/
		private function loginSuccessHandler(e:BaseNetEvent):void
		{		
			IO.traceLog("登录成功",ModelLocator.getInstance().player.nRoles,e.data[0]);
			
			NetSocket.getInstance().removeEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandle);
			
			ModelLocator.getInstance().gameStatus	=	ModelLocator.Gameing;
			
			var overTime : int = getTimer() - _time;
			
			var loginType:uint=e.data[0];
			
//			WaitingForScene.end();
			
			switch(loginType)
			{
				//登录失败
				case GamePlayer.LoginType_Fail:
					IO.traceLog("登录失败");
					loginUI.hide();
					//					trace("-------------1");
					break;
				//登录成功，无角色,创建角色
				case GamePlayer.LoginType_NoRole:
					SceneManager.isCreate = true;
					_create	=	true;
					loginUI.hide();
					loginUI.show({type:LoginUI.ShowRoleCreate})
					//					trace("-------------2");
					break;
				//登录成功，有角色，但没有选择角色
				case GamePlayer.LoginType_NotLoginRole:
					//					loginUI.hide();
					if(_create)
					{
						//ActSee.PostLoginStatus(22003,1,overTime);
						_time = getTimer();
					}
					
					
					var name:String=ModelLocator(e.target).player.wsName;
					SystemSender.getInstance().SelectRole(name);
					//					trace("-------------3");
					break;
				//登录成功，且选择了登录的角色
				case GamePlayer.LoginType_LoginRole:
					ActSee.PostLoginStatus(22005,1,overTime);
					//					trace("-------------开始等待");
//					WaitingForScene.start();
					loginUI.hide();
					this.recycle();//出口
					//					trace("-------------4");
					break;
			}
			
//			if(	null	!=	_resReadyCallBack	)
//								_resReadyCallBack();
		}
		
		//		//登录结束，进入游戏
		//		private function loginOver():void
		//		{
		//			this.removeAll();
		//			ModelLocator.getInstance().dispatchEvent(new LogicEvent(LogicEvent.LOGIN_COMPLETE));
		//		}
		
		//登陆失败
		private function loginFailHandler(e:BaseNetEvent):void
		{
			var		error:int	=	e.data[0];
			
			IO.traceLog("登录失败，error id:"+error);
			
			var errorStr:String=this.getLoginFailMsg(error)
			
			if(	error	==	51069)//防沉迷提示
			{
				if(LoginCallLater.AllSwfReady)
				{
					AlertTimeLoseUI.getInstance().showTimeLoseUI("0",AlertLogic.TIPSTYPE_SYSTEM_UNENTHRALL,errorStr);
				}
				else
				{
					UICompleteFunc	=	function():void
					{
						AlertTimeLoseUI.getInstance().showTimeLoseUI("0",AlertLogic.TIPSTYPE_SYSTEM_UNENTHRALL,errorStr);
					}
				}
			}
			else if(error	==	51001)//账户名不存在	, 重连下
			{
				NetMgr.netConnect(_loginInfo.ip,_loginInfo.port,socketConnectSucceedHandler);
				
				SystemSender.getInstance().LoginOtherWay(_loginInfo.sAccount,_loginInfo.sIdentity)
			}
			else
			{
				LoginAlert.showAlert(error.toString());
				NxLoaderProxy.hide();
//				WaitingForScene.end();
				LoginUI._loginContainer.visible = true;
			}
			
			showProtectionLoginUI( error );
		}
		
		private function showProtectionLoginUI( error : int ):void
		{
			//			51088 -- 您的帐号绑定的令牌密保已过期，请解除绑定或更换后再登录
			//			51089 -- 您的帐号绑定的令牌密保需要效验，请到会员中心操作
			//			51090 -- 您的令牌密保错误，禁止登录
			//			51091 -- 此帐号受令牌密保服务保护，请选择令牌密保方式登录
			
			if( error == 51088 || error == 51089 || error == 51090 || error == 51091)
			{
				_loginUI.showProtectionLogin();
			}
		}
		
		//重连
		private function securityErrorHandle(e:SecurityErrorEvent):void
		{
			NetMgr.netConnect(_loginInfo.ip,_loginInfo.port,socketConnectSucceedHandler);
			
			SystemSender.getInstance().LoginOtherWay(_loginInfo.sAccount,_loginInfo.sIdentity);
		}
		
//		130
//		
//		正在排队中……<br>目前所处位置：{@0:队列}队列第{@1:位置}位

		
		private function serverQueueHandler(e:BaseNetEvent):void
		{
			IO.traceLog("开始排队",e.data);
			
			var queueMsg:String	=	StaticIni.getSwfLangStrVar("130",e.data);
			AlertUI.showAlert(StaticIni.getSwfLangStr("MessageUI_Notice"),queueMsg);
		}
		
		//==============================服务器 通信 Start ==================
//		private function sendLoginMessage(loginInfo:Object):void
//		{
			//			if(_isNormalLogin)
			//			{
			//				IO.traceLog("正常登录,ip:",loginInfo.ip,"port:",loginInfo.port,"userName:",loginInfo.sAccount,"password:",loginInfo.sIdentity);
			//				NetMgr.netConnect(loginInfo.ip,loginInfo.port,socketConnectSucceedHandler);
			//				SystemSender.getInstance().Login(loginInfo.userName,loginInfo.password);	
			//			}
			//			else
			//			{
			//				IO.traceLog("联合运营登录,ip:",loginInfo.ip,"port:",loginInfo.port,"sAccount:",loginInfo.sAccount,"sIdentity:",loginInfo.sIdentity);
			//				NetMgr.netConnect(loginInfo.ip,loginInfo.port,socketConnectSucceedHandler);
			//				SystemSender.getInstance().LoginOtherWay(loginInfo.sAccount,loginInfo.sIdentity);
			//			}
//		}
		
		private function get loginUI():LoginUI
		{
			if(null		==	_loginUI)	
				_loginUI=new LoginUI();
			
			return _loginUI;
		}
		
		/**通过id获取，城堡标识*/
		private function getCastleById(castleId:int):String
		{
			var obj:Object=StaticIni.getIniObj("Castle_"+castleId);
			var name:String=obj["CastleNameID"];
			
			return name;
		}
		
		private function getServerSelectTip():String
		{
			return StaticIni.getSwfLangStr("UIStr_1000873");
		}
		
		private function getLoginStartMsg():String
		{
			return 	StaticIni.getSwfLangStr("正在登陆,请稍等...");
		}
		private function getLoginFailMsg(errorId:int):String
		{
			return StaticIni.getSwfLangStr(String(errorId));
		}
		private function getConnectErrorMsg():String
		{
			return StaticIni.getSwfLangStr("UIStr_1000868");
		}
		
		public function set readyCallBack(cb:Function):void
		{
			_resReadyCallBack=cb;
//			if(	null	!=	_resReadyCallBack	)
//				_resReadyCallBack();
		}
	}
}